<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Rag Hu
 * Created Time: 2019/8/16 19:33
 * Modified Time: 2019/8/16 19:33
 * Version: 2.0
 */

namespace App\Modules\DataCenter\Services;


use App\Exceptions\AllValidatorException;
use App\Lib\Utilities;
use App\Modules\Employee\Repositories\EmployeeRepository;
use App\Modules\Employee\Repositories\MyVisitHistoryRepository;
use App\Modules\Employee\Repositories\PortfolioRepository;
use App\Modules\Employee\Repositories\SalaryRepository;
use App\Modules\Employee\Repositories\UserLikeRepository;
use App\Modules\Inventory\Repositories\GoodsOrderRepository;
use App\Modules\MemberCard\Criterias\AppGetMemberCardListCriteria;
use App\Modules\MemberCard\Repositores\MemberCardFlowRepository;
use App\Modules\MemberCard\Repositores\MemberCardRepository;
use App\Modules\Order\Criterias\GetOrderPointCriteria;
use App\Modules\Order\Repositories\OrderCommentRepository;
use App\Modules\Order\Repositories\OrderItemRepository;
use App\Modules\Order\Repositories\OrderRepository;
use App\Modules\Order\Repositories\RoyaltyRepository;
use App\Modules\Service\Repositories\ServiceRepository;
use App\Modules\Store\Repositories\StoreRepository;
use App\Modules\System\Repositories\AmountFlowRepository;
use App\Modules\System\Repositories\UserStoreRepository;
use Flower\Core\Repository\Eloquent\BaseService;

class BarberStatisticsService extends BaseService
{
    protected $storeRepository;
    protected $userStoreRepository;
    protected $orderRepository;
    protected $goodsOrderRepository;
    protected $royaltyRepository;
    protected $userLikeRepository;
    protected $portfolioRepository;
    protected $myVisitHistoryRepository;
    protected $orderCommentRepository;
    protected $memberCardRepository;
    protected $memberCardFlowRepository;
    protected $orderItemRepository;
    protected $salaryRepository;
    protected $serviceRepository;
    protected $amountFlowRepository;
    protected $employeeRepository;

    public function __construct(StoreRepository $storeRepository,
                                UserStoreRepository $userStoreRepository,
                                OrderRepository $orderRepository,
                                GoodsOrderRepository $goodsOrderRepository,
                                RoyaltyRepository $royaltyRepository,
                                UserLikeRepository $userLikeRepository,
                                PortfolioRepository $portfolioRepository,
                                MyVisitHistoryRepository $myVisitHistoryRepository,
                                OrderCommentRepository $orderCommentRepository,
                                MemberCardRepository $memberCardRepository,
                                MemberCardFlowRepository $memberCardFlowRepository,
                                OrderItemRepository $orderItemRepository,
                                SalaryRepository $salaryRepository,
                                ServiceRepository $serviceRepository,
                                AmountFlowRepository $amountFlowRepository,
                                EmployeeRepository $employeeRepository)
    {
        $this->storeRepository = $storeRepository;
        $this->userStoreRepository = $userStoreRepository;
        $this->orderRepository = $orderRepository;
        $this->goodsOrderRepository = $goodsOrderRepository;
        $this->royaltyRepository = $royaltyRepository;
        $this->userLikeRepository = $userLikeRepository;
        $this->portfolioRepository = $portfolioRepository;
        $this->myVisitHistoryRepository = $myVisitHistoryRepository;
        $this->orderCommentRepository = $orderCommentRepository;
        $this->memberCardRepository = $memberCardRepository;
        $this->memberCardFlowRepository = $memberCardFlowRepository;
        $this->orderItemRepository = $orderItemRepository;
        $this->orderItemRepository = $orderItemRepository;
        $this->salaryRepository = $salaryRepository;
        $this->serviceRepository = $serviceRepository;
        $this->amountFlowRepository = $amountFlowRepository;
        $this->employeeRepository = $employeeRepository;
    }

    /**
     * 数据中心获取头部信息
     * @param $user_id
     * @param $store_id
     * @return array
     */
    public function getBarberDataCenterHeader($user_id, $store_id)
    {
        $store_name = $this->storeRepository->getStoreNameByid($store_id)->store_name;
        $user = $this->employeeRepository->find($user_id);
        $nick = $user->nick;
        $face = $user->picture()->first() ? $user->picture()->first()->image : null;
        $days = $this->userStoreRepository->getWorkDays($user_id, $store_id)->days;

        $date = date('Y-m-d', time());

//        $orders_num = $this->orderRepository->getBarberDateOrderNum($user_id, $store_id, $date);
//
//        $orders_amount = $this->orderRepository->getBarberDateOrderAmount($user_id, $store_id, $date);
//        $goods_sale_amount = $this->goodsOrderRepository->getBarberDateGoodsOrderAmount($user_id, $store_id, $date);
//        $amount = $orders_amount + $goods_sale_amount;

        $royalty_data = $this
            ->amountFlowRepository
            ->getBarberAmountFlow($user_id,$store_id,$date)
            ->get();
        $amount = $royalty_data->sum('real_price');
        $orders_num = $royalty_data->count();
        $royalty = $royalty_data->sum('barber_royalty');

        return [
            'store_name' => $store_name,
            'nick' => $nick,
            'face' => $face,
            'days' => $days,
            'orders_num' => $orders_num,
            'amount' => round($amount,0),
            'royalty' => round($royalty,0)
        ];
    }


    /**
     * 获取经营分析
     * @param $user_id
     * @param $store_id
     * @param $date_type
     * @return array
     */
    public function getBarberDataBusinessAnalysis($user_id, $store_id, $date_type)
    {
        $end_day = $this->formatDate($date_type);
        $service_data = $this->orderRepository->getServiceRateDate($store_id, $user_id, $end_day);
        $service_royalty = $this->orderRepository->getServiceTypeRoyalty($store_id, $user_id, $end_day);
        //处理服务分析数据
        $service_business = $this->dealServiceAnalysis($service_data, $service_royalty);

        $scissors_washing_service_count = $service_business['scissors_washing_service_count'];
        $scissors_washing_service_amount = $service_business['scissors_washing_service_amount'];
        $scissors_washing_service_royalty = $service_business['scissors_washing_service_royalty'];
        $ironing_service_count = $service_business['ironing_service_count'];
        $ironing_service_amount = $service_business['ironing_service_amount'];
        $ironing_service_royalty = $service_business['ironing_service_royalty'];
        $other_service_count = $service_business['other_service_count'];
        $other_service_amount = $service_business['other_service_amount'];
        $other_service_royalty = $service_business['other_service_royalty'];

        //办卡提成
        $royalty_data = $this->amountFlowRepository->getBarberAmountFlowGroup($user_id, $store_id, $end_day);

        $member_card_count = 0;
        $member_card_amount = 0;
        $member_card_royalty = 0;

        $goods_count = 0;
        $goods_amount = 0;
        $goods_royalty = 0;

        foreach ($royalty_data as $key => $value) {
            if ($value['category'] == 2) {
                $member_card_count = $value['count'];
                $member_card_amount = $value['amount'];
                $member_card_royalty = $value['royalty'];
            } elseif ($value['category'] == 3) {
                $goods_count = $value['count'];
                $goods_amount = $value['amount'];
                $goods_royalty = $value['royalty'];
            } else {

            }
        }

        return [
            [
                'name' => '剪洗',
                'type' => 'jx',
                'nums' => round($scissors_washing_service_count, 2),
                'amount' => round($scissors_washing_service_amount, 2),
                'profit' => round($scissors_washing_service_royalty, 2)
            ],
            [
                'name' => '烫染',
                'type' => 'tr',
                'nums' => round($ironing_service_count, 2),
                'amount' => round($ironing_service_amount, 2),
                'profit' => round($ironing_service_royalty, 2)
            ],
            [
                'name' => '其他',
                'type' => 'qt',
                'nums' => round($other_service_count, 2),
                'amount' => round($other_service_amount, 2),
                'profit' => round($other_service_royalty, 2)
            ],
            [
                'name' => '办卡',
                'type' => 'bk',
                'nums' => round($member_card_count, 2),
                'amount' => round($member_card_amount, 2),
                'profit' => round($member_card_royalty, 2)
            ],
            [
                'name' => '商品',
                'type' => 'sp',
                'nums' => round($goods_count, 2),
                'amount' => round($goods_amount, 2),
                'profit' => round($goods_royalty, 2)
            ],
        ];
    }

    /**
     * 经营数据详情
     * @param $user_id
     * @param $store_id
     * @param $date_type
     */
    public function getBarberDataBusinessAnalysisDetails($user_id, $store_id, $type, $date_type,$pageSize)
    {
        $end_day = $this->formatDate($date_type);
        switch ($type) {
            case 'jx':
                $data = $this
                    ->orderRepository
                    ->getOrderByServiceType($store_id,$user_id,$end_day,[7,9])
                    ->paginate($pageSize,['*']);
                break;
            case 'tr':
                $data = $this
                    ->orderRepository
                    ->getOrderByServiceType($store_id,$user_id,$end_day,[8,10])
                    ->paginate($pageSize,['*']);
                break;
            case 'qt':
                $data = $this
                    ->orderRepository
                    ->getOrderByServiceType($store_id,$user_id,$end_day,[11])
                    ->paginate($pageSize,['*']);
                break;
            case 'bk':
                $data = $this
                    ->amountFlowRepository
                    ->getBarberMemberCardAmountFlowAnalysis($store_id,$user_id,$end_day)
                    ->paginate($pageSize,['*']);
                break;
            case 'sp':
                $data = $this
                    ->goodsOrderRepository
                    ->getGoodsOrderAnalysis($store_id,$user_id,$end_day,[11])
                    ->paginate($pageSize,['*']);
                break;
            default:
                throw new AllValidatorException(['msg' => '错误的type值']);
        }

        return Utilities::dealPage($data);
    }

    /**
     * 获取经营数据
     * @param $user_id
     * @param $store_id
     */
    public function getBarberDataOverview($user_id, $store_id)
    {
        //今日日期
        $date = date('Y-m-d', time() );
        //七天前日期
        $pre_week_date = date('Y-m-d', time() - (86400 * 7));

//        $today_royalty_data = $this->royaltyRepository->getBarberRoyaltyDate($user_id, $store_id, $date);
//        $pre_royalty_data = $this->royaltyRepository->getBarberRoyaltyDate($user_id, $store_id, $pre_week_date);

        $today_royalty_data = $this->amountFlowRepository->getBarberAmountFlow($user_id, $store_id, $date)->get();

        $pre_royalty_data = $this->amountFlowRepository->getBarberAmountFlow($user_id, $store_id, $pre_week_date)->get();

        //今日订单数======================================================================
        $orders_num = $today_royalty_data->count();
        //上周订单数
        $pre_week_orders_num = $pre_royalty_data->count();
        //订单数同期增长
        $orders_num_increase = $orders_num - $pre_week_orders_num;
        //是否上升
        $orders_num_increase_up = $this->isUp($orders_num_increase);

        //今日订单额======================================================================
        $orders_amount = $today_royalty_data->sum('real_price');
        //上周订单额
        $pre_week_orders_amount = $pre_royalty_data->sum('real_price');

        //今日客单价============================================================================
        $average_price = $orders_num==0?0:round(($orders_amount/$orders_num),2);
        //上周客单价
        $pre_week_average_price = $pre_week_orders_num==0?0:round(($pre_week_orders_amount/$pre_week_orders_num),2);
        //客单价增长
        $average_price_increase = $average_price - $pre_week_average_price;
        //是否上升
        $average_price_increase_up = $this->isUp($average_price_increase);

        //今日粉丝数======================================================================
        $fans_num = $this->userLikeRepository->getBarberDateFansNum($user_id, $store_id, $date);
        //上周粉丝数
        $pre_week_fans_num = $this->userLikeRepository->getBarberDateFansNum($user_id, $store_id, $pre_week_date);
        //粉丝数同期增长
        $fans_num_increase = $fans_num - $pre_week_fans_num;
        //是否上升
        $fans_num_increase_up = $this->isUp($fans_num_increase);

        //今日访客数
        $visitor_num = $this->myVisitHistoryRepository->getBarberDateVisitorNum($user_id,$store_id, $date);
        //上周访客数
        $pre_week_visitor_num = $this->myVisitHistoryRepository->getBarberDateVisitorNum($user_id,$store_id, $pre_week_date);
        //访客数同期增长
        $visitor_num_increase = $visitor_num - $pre_week_visitor_num;
        //是否上升
        $visitor_num_increase_up = $this->isUp($visitor_num_increase);

        //今日转化率======================================================================
        $conversion_rate = $this->myVisitHistoryRepository->getBarberDateVisitorOrderNum($user_id,$store_id, $date);
        //上周转化率
        $pre_week_conversion_rate = $this->myVisitHistoryRepository->getBarberDateVisitorOrderNum($user_id, $store_id,$pre_week_date);
        //转化率增长
        $conversion_rate_increase = round($conversion_rate - $pre_week_conversion_rate,1);
        //是否上升
        $conversion_rate_increase_up = $this->isUp($conversion_rate_increase);

        //今日好评率=======================================================================
        $good_comment_rate = $this->orderCommentRepository->getBarberDateGoodCommentRate($user_id, $store_id, $date);
        //上周好评率
        $pre_week_good_comment_rate = $this->orderCommentRepository->getBarberDateGoodCommentRate($user_id, $store_id, $pre_week_date);
        //好评率增长
        $good_comment_rate_increase = $good_comment_rate - $pre_week_good_comment_rate;
        //是否上升
        $good_comment_rate_increase_up = $this->isUp($good_comment_rate_increase);

        //今日新增会员卡===================================================================
        $member_card_num = $this->memberCardRepository->getBarberDateMemberCardNum($user_id, $store_id, $date);
        //上周新增会员卡
        $pre_week_member_card_num = $this->memberCardRepository->getBarberDateMemberCardNum($user_id, $store_id, $pre_week_date);
        //会员卡数同期增长
        $member_card_num_increase = $member_card_num - $pre_week_member_card_num;
        //是否上升
        $member_card_num_increase_up = $this->isUp($member_card_num_increase);

        //今日指定用户占比
        $appoint_order_rate = $this->orderRepository->getBarberDateAppointOrderRate($user_id, $store_id, $date);
        //上周指定用户占比
        $pre_week_appoint_order_rate = $this->orderRepository->getBarberDateAppointOrderRate($user_id, $store_id, $pre_week_date);
        //指定用户占比增长
        $appoint_order_rate_increase = round($appoint_order_rate - $pre_week_appoint_order_rate,1);
        //是否上升
        $appoint_order_rate_increase_up = $this->isUp($appoint_order_rate_increase);

        //今日作品数======================================================================
        $portfolio_num = $this->portfolioRepository->getBarberDatePortfolioNum($user_id, $store_id, $date);
        //上周作品数
        $pre_week_portfolio_num = $this->portfolioRepository->getBarberDatePortfolioNum($user_id, $store_id, $pre_week_date);
        //作品数同期增长
        $portfolio_num_increase = $portfolio_num - $pre_week_portfolio_num;
        //是否上升
        $portfolio_num_increase_up = $this->isUp($portfolio_num_increase);


        return [
            [
                'title' => '订单数',
                'count' => $orders_num,
                'unit' => '笔',
                'rate' => abs($orders_num_increase),
                'is_up' => $orders_num_increase_up

            ],
            [
                'title' => '平均客单价',
                'count' => $average_price,
                'unit' => '元',
                'rate' => abs($average_price_increase),
                'is_up' => $average_price_increase_up
            ],
            [
                'title' => '新增粉丝',
                'count' => $fans_num,
                'unit' => '个',
                'rate' => abs($fans_num_increase),
                'is_up' => $fans_num_increase_up
            ],
            [
                'title' => '访客数',
                'count' => $visitor_num,
                'unit' => '个',
                'rate' => abs($visitor_num_increase),
                'is_up' => $visitor_num_increase_up
            ],
            [
                'title' => '转化率',
                'count' => round($conversion_rate*100),
                'unit' => '%',
                'rate' => abs($conversion_rate_increase),
                'is_up' => $conversion_rate_increase_up
            ],
            [
                'title' => '好评率',
                'count' => round($good_comment_rate*100),
                'unit' => '%',
                'rate' => abs($good_comment_rate_increase),
                'is_up' => $good_comment_rate_increase_up
            ],
            [
                'title' => '新增会员',
                'count' => $member_card_num,
                'unit' => '个',
                'rate' => abs($member_card_num_increase),
                'is_up' => $member_card_num_increase_up
            ],
            [
                'title' => '指定用户比',
                'count' => round($appoint_order_rate*100),
                'unit' => '%',
                'rate' => abs($appoint_order_rate_increase),
                'is_up' => $appoint_order_rate_increase_up
            ],
            [
                'title' => '新发作品',
                'count' => $portfolio_num,
                'unit' => '个',
                'rate' => abs($portfolio_num_increase),
                'is_up' => $portfolio_num_increase_up
            ],
        ];

    }

    //计算同期占比
    protected function increaseCalculation($now, $pre_week)
    {
        $growth_rate = 0;
        if ($pre_week == 0) {
            if ($now == 0) {
                $growth_rate = 0;
            } else {
                $growth_rate = 1;
            }
        } else {
            $growth_rate = round(($now - $pre_week) / $pre_week, 2);
        }

        return $growth_rate;
    }

    //判断上涨
    public function isUp($num)
    {
        if($num>0){
            return 2;
        }elseif ($num<0){
            return 1;
        }else{
            return 0;
        }
    }

    /**
     * 获取理发师访客记录
     * @param $user_id
     */
    public function getBarberVisitorRecord($user_id, $store_id, $dateType)
    {
        $dateList = $this->getStartEndDayByDateType($dateType);

        $graphList = $this->myVisitHistoryRepository->getBarberVisitorGraphData($user_id, $store_id, $dateList['start_date'], $dateList['end_date']);

        $user_id_array = $this->userStoreRepository->getSameLevel($user_id, $store_id);

        $user_id_array_string = (count($user_id_array) == 1) ? $user_id_array[0] : implode(',', $user_id_array);

        $graphListAvg = empty($user_id_array) ? [] : $this->myVisitHistoryRepository->getBarberVisitorGraphData($user_id_array_string, $store_id, $dateList['start_date'], $dateList['end_date']);

        $result['graph_list'] = $this->visitorFormatterData($graphList, $dateList['start_date'], $dateList['end_date'], $graphListAvg, count($user_id_array));

        $result['visitor_list'] = $this->myVisitHistoryRepository->getList($user_id, $store_id, $dateList['start_date'], $dateList['end_date'], 0);

        return $result;


    }

    /**
     * 根据日期类型获取开始和结束日期
     * @param $dateType
     * @return mixed
     */
    public function getStartEndDayByDateType($dateType)
    {
        $dateType = empty($dateType) ? 0 : $dateType;
        $list['start_date'] = config('constant.dataCenter.isToday') ? date('Y-m-d', time()) : date('Y-m-d', strtotime('-1 day'));
        switch ($dateType) {
            case 0:
                $list['end_date'] = $list['start_date'];
                break;
            case 1:
                $list['end_date'] = date('Y-m-d', strtotime($list['start_date'] . ' -6 day'));
                break;
            case 2:
                $list['end_date'] = date('Y-m-d', strtotime($list['start_date'] . ' -29 day'));
                break;
            case 3:
                $list['end_date'] = date('Y-m-d', strtotime($list['start_date'] . ' -1 years'));
                break;
        }
        return $list;
    }


    /**
     * 格式化访客数据的画图数据
     * @param $list
     * @param $startDate
     * @param $endDate
     * @return array
     * @author Happy dong
     * @modifiedTime 2019-08-18 22:37
     */
    public function visitorFormatterData($list, $startDate, $endDate, $avgList, $count = 1)
    {
        if ($startDate == $endDate) {
            $resultList = array_map(function ($v) use ($list, $avgList, $count) {
                return [
                    'time' => $v,
                    'count' => empty($list) ? 0 : (isset($list['hour' . $v]) ? $list['hour' . $v] : 0),
                    'avg_count' => empty($avgList) ? 0 : (isset($avgList['hour' . $v]) ? round($avgList['hour' . $v] / $count, 0) : 0),
                ];
            }, range(3, 24, 3));
        } else {
            $dateList = [];
            $startDateSeconds = strtotime($startDate);
            $endDateSeconds = strtotime($endDate);
            while ($startDateSeconds >= $endDateSeconds) {
                $dateList[] = date('m-d', $startDateSeconds);
                $startDateSeconds -= 86400;
            }
            $list = empty($list) ? [] : array_column($list, null, 'times');
            $resultList = array_map(function ($v) use ($list, $avgList, $count) {
                return [
                    'time' => $v,
                    'count' => empty($list) ? 0 : (isset($list[$v]) ? $list[$v]['visitor_count'] : 0),
                    'avg_count' => empty($avgList) ? 0 : (isset($avgList[$v]) ? round($avgList[$v]['visitor_count'] / $count, 0) : 0),
                ];
            }, $dateList);
        }

        return $resultList;
    }

    /**
     * 访客列表
     * @param $storeId
     * @param int $dateType
     * @return VisitHistoryRepository[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Support\Collection
     */
    public function getVisitorList($user_id, $store_id, $dateType, $pageSize)
    {

        $dateList = $this->getStartEndDayByDateType($dateType);

        $list = $this->myVisitHistoryRepository->getList($user_id, $store_id, $dateList['start_date'], $dateList['end_date'], 1, $pageSize);
        $list = Utilities::dealPage($list);
        return $list;
    }

    /**订单列表
     * @param $storeId
     * @param $pageSize
     * @param int $dateType
     * @return mixed
     * @throws \Flower\Core\Repository\Exceptions\RepositoryException
     */
    public function getOrderList($user_id, $store_id, $pageSize, $dateType = 0)
    {
        $dateList = $this->getStartEndDayByDateType($dateType);
        return $this->orderRepository->getOrderListByDays($store_id, $dateList['start_date'], $dateList['end_date'], false, $pageSize, $user_id);
    }

    /**
     * 订单数据
     * @param $storeId
     * @param int $dateType
     * @return mixed
     * @throws \Flower\Core\Repository\Exceptions\RepositoryException
     */
    public function getOrderData($user_id, $store_id, $page_size, $date_type)
    {
        $dateList = $this->getStartEndDayByDateType($date_type);

        $OnlineGraphList = $this->orderRepository->getOrderGraphData($store_id, $dateList['start_date'], $dateList['end_date'], true, $user_id);
        $offlineGraphList = $this->orderRepository->getOrderGraphData($store_id, $dateList['start_date'], $dateList['end_date'], false, $user_id);

        $barberIdList = $this->userStoreRepository->getSameLevel($user_id, $dateList['start_date'], $dateList['end_date']);

        $storeIds = (count($barberIdList) == 1) ? $barberIdList[0] : implode(',', $barberIdList);

        $graphListAvg = empty($storeIds) ? [] : $this->orderRepository->getOrderGraphData($storeIds, $dateList['start_date'], $dateList['end_date'], false, $user_id);

        $result['graph_list'] = $this->graphFormatterData($OnlineGraphList, $dateList['start_date'], $dateList['end_date'], $graphListAvg, 'order', count($barberIdList), $offlineGraphList);
        $result['order_list'] = $this->orderRepository->getOrderListByDays($store_id, $dateList['start_date'], $dateList['end_date'], true, $page_size, $user_id)->toArray();
        return $result;

    }

    /**
     * 订单数据饼图
     * @param $storeId
     * @param int $dateType
     * @return array
     */
    public function getPieChartOrderData($user_id, $storeId, $dateType)
    {
        $dateList = $this->getStartEndDayByDateType($dateType);
        $list = $this->orderRepository->getPieChartData($storeId, $dateList['start_date'], $dateList['end_date'], $user_id);
        $result = [
            'online_count'  => empty($list[1]) ? 0 : $list[1]['count'],
            'offline_count' => empty($list[2]) ? 0 : $list[2]['count'],
            'store_count' => empty($list[3]) ? 0 : $list[3]['count'],
            'card_count' => empty($list[4]) ? 0 : $list[4]['count'],
            'total_count'   => (empty($list[1]['count']) ? 0 : $list[1]['count']) + (empty($list[2]['count']) ? 0 : $list[2]['count']) + (empty($list[3]['count']) ? 0 : $list[3]['count']) + (empty($list[4]['count']) ? 0 : $list[4]['count'])
        ];
        return $result;
    }


    /**
     * 数据中心会员卡数据
     * @param $storeId
     * @param int $dateType
     * @return array
     * @throws \Flower\Core\Repository\Exceptions\RepositoryException
     */
    public function getMemberCardDataCenter($user_id, $storeId, $dateType)
    {
        $dateList = $this->getStartEndDayByDateType($dateType);
        $newCount = $this->memberCardRepository->getMemberCardCount($storeId, $dateList['start_date'], $dateList['end_date'], true, $user_id);
        $totalCount = $this->memberCardRepository->getStoreMemberCradNum($storeId, 1, $user_id)->get()->count();

        $list = [
            'new_count' => empty($newCount) ? 0 : $newCount->card_count,
            'total_count' => empty($totalCount) ? 0 : $totalCount,
        ];

        $list['flow_list'] = $this->memberCardFlowRepository->getFlowList($storeId, $dateList['start_date'], $dateList['end_date'], true, 10, $user_id)->toArray();
        return $list;
    }

    public function getFlowList($storeId, $pageSize, $dateType = 0, $user_id)
    {
        $dateList = $this->getStartEndDayByDateType($dateType);
        return $this->memberCardFlowRepository->getFlowList($storeId, $dateList['start_date'], $dateList['end_date'], false, $pageSize, $user_id);

    }


    /**
     * 获取指定用户数据
     * @param $user_id
     * @param $store_id
     * @param $date_type
     * @param $pageSize
     * @return array
     * @throws AllValidatorException
     * @throws \Flower\Core\Repository\Exceptions\RepositoryException
     */
    public function getOrderPointData($user_id, $store_id, $date_type, $pageSize)
    {
        if ($date_type == 0) {
            $start_time = 0;
            $end_time = 1;
        } elseif ($date_type == 1) {
            $start_time = 0;
            $end_time = 7;
        } elseif ($date_type == 2) {
            $start_time = 0;
            $end_time = 30;
        } else {
            throw new AllValidatorException(['msg' => '错误的时间']);
        }
        $data = $this
            ->orderRepository
            ->pushCriteria(new GetOrderPointCriteria($start_time, $end_time, $store_id, $user_id))
            ->paginate($pageSize, ['*']);

        return Utilities::dealPage($data);
    }

    /**
     * 获取指定用户数据
     * @param $user_id
     * @param $store_id
     * @param $date_type
     * @param $pageSize
     * @return array
     * @throws AllValidatorException
     * @throws \Flower\Core\Repository\Exceptions\RepositoryException
     */
    public function getOrderPoint($user_id, $store_id, $date_type)
    {
        if ($date_type == 0) {
            $start_time = 0;
            $end_time = 1;
        } elseif ($date_type == 1) {
            $start_time = 0;
            $end_time = 7;
        } elseif ($date_type == 2) {
            $start_time = 0;
            $end_time = 30;
        } else {
            throw new AllValidatorException(['msg' => '错误的时间']);
        }
        return $this
            ->orderRepository
            ->pushCriteria(new GetOrderPointCriteria($start_time, $end_time, $store_id, $user_id))
            ->get()
            ->take(5);
    }

    /**
     * 服务排名数据
     * @param $storeId
     * @param int $dateType
     * @param int $isAmount
     * @param int $isLimit
     * @return mixed
     */
    public function getOrderServiceData($user_id, $storeId, $dateType, $isAmount = 0, $isLimit = 1)
    {
        $dateList = $this->getStartEndDayByDateType($dateType);
        return $this->serviceRepository->getBarberOrderServiceAmountCount($storeId, $dateList['start_date'], $dateList['end_date'], $isAmount, $isLimit, $user_id);
    }

    /**
     * 获取订单服务列表
     * @param $storeId
     * @param $serviceId
     * @param $pageSize
     * @param int $dateType
     * @return mixed
     * @throws \Flower\Core\Repository\Exceptions\RepositoryException
     */
    public function getOrderServiceList($user_id, $storeId, $serviceId, $pageSize, $dateType = 0)
    {
        $dateList = $this->getStartEndDayByDateType($dateType);
        $list = $this->orderItemRepository->getOrderServiceList($storeId, $serviceId, $dateList['start_date'], $dateList['end_date'], $pageSize, $user_id)->toArray();

        if (!empty($list['data'])) $list['data'] = array_map(function ($v) {
            return $v['order'];
        }, $list['data']);

        return $list;
    }

    /**
     * 数据中心工资列表
     * @param $storeId
     * @return mixed
     */
    public function getCenterUserSalaryList($user_id, $store_id)
    {
        //获取理发师信息
        $barber_info = $this->employeeRepository->getUserInfo($user_id);
        $barber_name = $barber_info->nick;
        $barber_face = $barber_info->picture ? $barber_info->picture->image : null;
        //获取总工资
        $gross_wage = $this->salaryRepository->getBarberGrossWage($user_id, $store_id);

        //获取12个月工资详情
        $wage_list = $this->salaryRepository->getBarberGrossWageList($user_id, $store_id);

        return [
            'barber_name' => $barber_name,
            'barber_face' => $barber_face,
            'gross_wage' => $gross_wage,
            'wage_list' => $wage_list
        ];
    }

    /**
     * 获取某月工资详情
     * @param $user_id
     * @param $store_id
     * @param $month
     */
    public function getCenterUserMonthSalaryList($user_id, $store_id, $month)
    {
        $base_wage = $this->userStoreRepository->getBaseWage($user_id, $store_id);

        $wage_list = $this->salaryRepository->getBarberMonthGrossWageList($user_id, $store_id, $month);

        $todayRoyalty = (new RoyaltyRepository())->getUserStoreTodayRoyalty($user_id, $store_id, [], date('Y-m-d',time()));
        // 计算员工的基本工资

        $baseSalary = (new UserStoreRepository())->getUserDailySalary($store_id, $user_id, config('constant.role.barber'), time());

        $today_wage =  $todayRoyalty['amount'] + $baseSalary;

        $wage_list[] = [
            'royalty' => $today_wage,
            'data' => date('m-d',time())
        ];

        return [
            'base_wage' => $base_wage,
            'wage_list' => $wage_list
        ];
    }


    /**
     * 格式化访客数据的画图数据
     * @param $list @线上/其他数据
     * @param $startDate @开始日期
     * @param $endDate @结束日期
     * @param $avgList @平均数据
     * @param $filed @字段名称
     * @param int $count @同级店铺数
     * @param null $offline @线下数据
     * @return array
     * @author Happy dong
     * @modifiedTime 2019-08-19 15:40
     */
    public function graphFormatterData($list, $startDate, $endDate, $avgList, $filed, $count = 1, $offline = null)
    {
        if ($startDate == $endDate) {
            $resultList = array_map(function ($v) use ($list, $avgList, $count, $offline) {
                $res = [
                    'time' => $v,
                    'count' => empty($list) ? 0 : (isset($list['hour' . $v]) ? $list['hour' . $v] : 0),
                    'avg_count' => empty($avgList) ? 0 : (isset($avgList['hour' . $v]) ? round($avgList['hour' . $v] / $count, 0) : 0),
                ];
                if (isset($offline)) {
                    $res['offline_count'] = empty($list) ? 0 : (isset($list['hour' . $v]) ? $list['hour' . $v] : 0);
                }
                return $res;
            }, range(3, 24, 3));
        } else {
            $dateList = [];
            $startDateSeconds = strtotime($startDate);
            $endDateSeconds = strtotime($endDate);
            while ($startDateSeconds >= $endDateSeconds) {
                $dateList[] = date('Y-m-d', $endDateSeconds);
                $endDateSeconds += 86400;
            }
            $list = empty($list) ? [] : array_column($list, null, 'times');
            $resultList = array_map(function ($v) use ($list, $avgList, $filed, $count, $offline) {
                $res = [
                    'time' => substr($v, -5),
                    'count' => empty($list) ? 0 : (isset($list[$v]) ? $list[$v][$filed . '_count'] : 0),
                    'avg_count' => empty($avgList) ? 0 : (isset($avgList[$v]) ? round($avgList[$v][$filed . '_count'] / $count, 0) : 0),
                ];
                if (isset($offline)) {
                    $res['offline_count'] = empty($list) ? 0 : (isset($list[$v]) ? $list[$v][$filed . '_count'] : 0);
                }
                return $res;
            }, $dateList);
        }
        return $resultList;

    }

    /**
     * 理发师理发师控制台头部信息
     * @param $storeId
     * @param $userId
     * @param $roleType
     * @return mixed
     */
    public function getStoreOrBerberControlHeaderInfo($storeId, $userId, $roleType)
    {
        $userId = ($roleType == config('constant.role.barber')) ? $userId : 0;
        // 获取理发师今日营业额

        $result['turnOver'] = $this->getTodayTurnOver($storeId, $userId);
        // 获取当前预约的人数
        $result['orderAppointCount'] = $this->orderRepository->getAppointmentCount($storeId, $userId);
        // 获取今日完成订单数
        $result['orderFinishedCount'] = $this->orderRepository->getOrderCount($storeId, $userId, 2);
        return $result;
    }

    /**
     * 计算店铺或者理发师的营业额
     * @param $storeId
     * @param $userId
     * @return mixed
     * @author Happy dong
     * @modifiedTime 2019-09-11 20:11
     */
    public function getTodayTurnOver($storeId, $userId)
    {
        $orderAmount = $this->orderRepository->getOrderAmount($storeId, $userId);
        $saleAmount = $this->goodsOrderRepository->getGoodsSaleAmount($storeId, $userId);
        $memberCardAmount = $this->memberCardFlowRepository->getMemberCardSaleAmount($storeId, $userId);

        $total = $orderAmount + $memberCardAmount + $saleAmount;
        return $total;

    }

    /**
     * 格式化时间
     * @param $date_type
     * @return false|string
     */
    protected function formatDate($date_type)
    {
        if ($date_type == 0) {
            $end_day = date('Y-m-d', time());
        } elseif($date_type==1) {
            $end_day = date('Y-m-d', time() - (7 * 86400));
        }else{
            $end_day = date('Y-m-d', time() - (30 * 86400));
        }
        return $end_day;
    }

    /**
     * 处理服务分析数据
     * @param $service_data
     * @param $service_royalty
     */
    protected function dealServiceAnalysis($service_data, $service_royalty)
    {
        $scissors_washing_service_count = 0;
        $scissors_washing_service_amount = 0;
        $scissors_washing_service_royalty = 0;

        $ironing_service_count = 0;
        $ironing_service_amount = 0;
        $ironing_service_royalty = 0;

        $other_service_count = 0;
        $other_service_amount = 0;
        $other_service_royalty = 0;

        foreach ($service_data as $key => $value) {
            if ($value['type'] == 8 || $value['type'] == 10) {
                $ironing_service_count = $ironing_service_count + $value['count'];
                $ironing_service_amount = $ironing_service_amount + $value['amount'];
            } elseif ($value['type'] == 7 || $value['type'] == 9) {
                $scissors_washing_service_count = $scissors_washing_service_count + $value['count'];
                $scissors_washing_service_amount = $scissors_washing_service_amount + $value['amount'];
            } else {
                $other_service_count = $other_service_count + $value['count'];
                $other_service_amount = $other_service_amount + $value['amount'];
            }
        }

        foreach ($service_royalty as $key => $value) {
            if ($value['type'] == 7 || $value['type'] == 9) {
                $royalty = array_sum(array_map(function ($val) {
                    return $val['amount'];
                }, $value['royalty']->toArray()));
                $scissors_washing_service_royalty = $scissors_washing_service_royalty + $royalty;
            } elseif ($value['type'] == 8 || $value['type'] == 10) {
                $royalty = array_sum(array_map(function ($val) {
                    return $val['amount'];
                }, $value['royalty']->toArray()));
                $ironing_service_royalty = $ironing_service_royalty + $royalty;
            } else {
                $royalty = array_sum(array_map(function ($val) {
                    return $val['amount'];
                }, $value['royalty']->toArray()));
                $other_service_royalty = $other_service_royalty + $royalty;
            }
        }

        return [
            'ironing_service_count' => $ironing_service_count,
            'ironing_service_amount' => $ironing_service_amount,
            'ironing_service_royalty' => $ironing_service_royalty,

            'scissors_washing_service_count' => $scissors_washing_service_count,
            'scissors_washing_service_amount' => $scissors_washing_service_amount,
            'scissors_washing_service_royalty' => $scissors_washing_service_royalty,

            'other_service_count' => $other_service_count,
            'other_service_amount' => $other_service_amount,
            'other_service_royalty' => $other_service_royalty,

        ];
    }


}